from django.conf import settings
from ..user.models import *
from utils.Mixin import *
from django.shortcuts import render, redirect, reverse, HttpResponse
from django.views import View


import xlrd
import tkinter as tk
from tkinter import filedialog
import time
# Create your views here.

import os,os.path
import zipfile
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from utils.Mixin import LoginRequiredMixin



def index(request):
    return render(request, 'index.html')

class push_handle(LoginRequiredMixin, View):
    def get(self, request):
        return redirect(reverse('ITEM:index'))

    def post(self, request):
        username = request.POST.get('username')
        # print(username)
        # if username == None or username=='':
        #     return HttpResponse("请先登录")
        push_user = User.objects.get(username=username)
        document = request.FILES['document']
        if document == '' or document == None:
            return HttpResponse("请选择文件")
        document_save_path = '%s/documents/%s'%(settings.MEDIA_ROOT, document.name)
        with open(document_save_path, 'wb') as f1:
            for content in document.chunks():
                f1.write(content)

        push_user.is_push = True
        push_user.save()
        # push_count += 1
        #return redirect(reverse('ITEM:index', {'message':'恭喜您,文件上传成功!!!'}))
        return render(request, 'index.html', {'message':'恭喜您,文件上传成功!!!'})

class get_view(View):
    def get(self, request):
        count = User.objects.filter(is_push=0).count()
        return render(request, 'start.html', {'count':count})
    def post(self, request):
        email = request.POST.get('email')
        documents_path = '%s\documents' % (settings.MEDIA_ROOT)
        zip_documents_path = '%s\documents.zip' % (settings.MEDIA_ROOT)

        not_push_text = "   目前还有以下人没交： "
        not_push_users = User.objects.filter(is_push=0)
        for user in not_push_users:
            not_push_text += user.first_name + ', '
        send_to_manager(email, zip_documents_path, not_push_text)
        if email=="877003243@qq.com":
            users = User.objects.all()
            for user in users:
                user.is_push = False
                user.save()

            del_dir(documents_path)
        return render(request, 'index.html', {'message': '已将周总结发送至您的邮箱'})


def add_user(request):
    root = tk.Tk()
    root.withdraw()
    file_path = filedialog.askopenfilename()
    print(file_path)
    work_book = xlrd.open_workbook(file_path)
    sheetNames = work_book.sheet_names()
    name_index = ""
    email_index = ""
    number_index = ""
    for name in sheetNames:
        sheet = work_book.sheet_by_name(name)

        for index in range(len(sheet.row_values(0))):
            if sheet.row_values(0)[index] == "姓名":
                name_index = index
            if sheet.row_values(0)[index] == "邮箱":
                email_index = index
            if sheet.row_values(0)[index] == "学号":
                number_index = index
        if name_index == "" or email_index == "" or number_index=="":
            continue
        insert_user(sheet, name_index, email_index, number_index)
        return redirect(reverse('ITEM:index'))

def insert_user(sheet, name_index, email_index, number_index):
    for i in range(len(sheet.col_values(name_index)))[1:]:

        username =int(sheet.row_values(i)[number_index])
        first_name = sheet.row_values(i)[name_index]
        email = sheet.row_values(i)[email_index]
        print(username, first_name, email)
        User.objects.create_user(username=username, first_name=first_name, password=username, email=email)


def push_listen(create_time):
    print("args=",create_time)
    sum_num = User.objects.count()
    sleep_time = 7
    email_time = 60
    while True:
        push_num = User.objects.filter(is_push=True).count()
        if (push_num < sum_num) and ((time.time() - create_time) > email_time):
            print(time.time())
            print(time.time() - create_time)
            create_time = time.time()

            remind_users = User.objects.filter(is_push=False)
            for remind_user in remind_users:
                print('send', remind_user.first_name)
                send_to_user(remind_user.email, remind_user.first_name)
        elif push_num == sum_num :
            documents_path = '%s\documents'%(settings.MEDIA_ROOT)
            zip_documents_path = '%s\documents.zip'%(settings.MEDIA_ROOT)
            zip_dir(documents_path, zip_documents_path)
            send_to_manager("877003243@qq.com", zip_documents_path)
            users = User.objects.all()
            for user in users:
                user.is_push = False
                user.save()

            del_dir(documents_path)
            break

        elif (push_num < sum_num) and ((time.time() - create_time) < email_time):
            time.sleep(sleep_time)

class start_upload(View):
    def get(self,request):

        create_time = time.time()
        push_listen(create_time)
        return HttpResponse([u"hello".encode('utf8')])


def send_to_user( email, content):
    username = '13986717767@163.com'
    password = 'Tuzhipeng00'
    sender = username
    receivers = email

    # 如名字所示： Multipart就是多个部分
    msg = MIMEMultipart()
    msg['Subject'] = '%s,你的周总结没有上传哦~' % content
    msg['From'] = sender
    msg['To'] = receivers

    # 下面是文字部分，也就是纯文本
    puretext = MIMEText('请尽快发送')
    msg.attach(puretext)

    try:
        client = smtplib.SMTP_SSL("smtp.163.com", 465)
        client.login(username, password)
        client.sendmail(sender, receivers, msg.as_string())
        client.quit()
    except smtplib.SMTPException as e:
        print(e)

def del_dir(path):
    ls = os.listdir(path)
    for i in ls:
        c_path = os.path.join(path, i)
        if os.path.isdir(c_path):
            del_dir(c_path)
        else:
            os.remove(c_path)

def zip_dir(dirname, zipfilename):
    filelist = []
    if os.path.isfile(dirname):
        filelist.append(dirname)
    else:
        for root, dirs, files in os.walk(dirname):
            for name in files:
                filelist.append(os.path.join(root, name))
    zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
    for tar in filelist:
        arcname = tar[len(dirname):]
        zf.write(tar, arcname)
    zf.close()

def send_to_manager( manager_email, zip1, not_push_text=""):
    username = '13986717767@163.com'
    password = 'Tuzhipeng00'
    sender = username
    receivers = manager_email

    # 如名字所示： Multipart就是多个部分
    msg = MIMEMultipart()
    msg['Subject'] = '周总结到啦！'
    msg['From'] = sender
    msg['To'] = receivers

    # 下面是文字部分，也就是纯文本
    puretext = MIMEText('主任，小的把周总结压缩包给您现行奉上~' + not_push_text)
    msg.attach(puretext)

    # 首先是xlsx类型的附件
    xlsxpart1 = MIMEApplication(open(zip1, 'rb').read())
    xlsxpart1.add_header('Content-Disposition', 'attachment', filename='周总结.zip')

    # xlsxpart2 = MIMEApplication(open(zip2, 'rb').read())
    # xlsxpart2.add_header('Content-Disposition', 'attachment', filename='pic2.zip')
    msg.attach(xlsxpart1)
    # msg.attach(xlsxpart2)

    try:
        client = smtplib.SMTP_SSL("smtp.163.com", 465)
        client.login(username, password)
        client.sendmail(sender, receivers, msg.as_string())
        client.quit()
    except smtplib.SMTPException as e:
        print(e)


